package com.sikaryofficial.qrcode.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.utils.PageUtil;
import com.sikaryofficial.common.core.web.controller.BaseController;
import com.sikaryofficial.common.core.web.domain.PageResult;
import com.sikaryofficial.qrcode.manager.DownloadManager;
import com.sikaryofficial.system.api.model.download.DownloadListPageReq;
import com.sikaryofficial.system.api.model.download.DownloadTaskDTO;
import com.sikaryofficial.system.api.model.download.StatusDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 下载任务Controller
 *
 * @author qinjinyuan
 * @date 2024-01-12
 */
@RestController
@RequestMapping("/downloadTask")
@Api(tags = "下载任务管理")
@Slf4j
public class DownloadTaskController extends BaseController {
    @Autowired
    private DownloadManager downloadManager;

    /**
     * 某个具体任务状态
     */
    @GetMapping("/latest/status/{objectId}")
    @ApiOperation(value = "刷新产品二维码最新任务状态")
    public R<StatusDTO> latestTaskStatus(@PathVariable(name = "objectId") Long objectId) {
        return R.ok(downloadManager.latestTaskStatus(objectId));
    }

    /**
     * 查询下载任务列表
     */
    @PostMapping("/listPage")
    @ApiOperation(value = "下载任务列表")
    public PageResult<DownloadTaskDTO> listByObjectId(@RequestBody DownloadListPageReq req) {
        IPage<DownloadTaskDTO> page = downloadManager.listByObjectId(req);
        return PageUtil.success(page.getRecords(), page.getTotal());
    }

    /**
     * 下载任务文件
     */
    @GetMapping("/download/{taskId}")
    @ApiOperation(value = "下载任务文件")
    public void downloadById(HttpServletResponse response, @PathVariable(name = "taskId") Long taskId) {
        if (Objects.isNull(taskId) || taskId <= 0) {
            throw new ServiceException("the input taskId is empty | zero ");
        }
        try {
            downloadManager.downloadById(response, taskId);
        } catch (Exception e) {
            log.error("downloadById:{}", e);
            throw new ServiceException("download error."+e.getMessage());
        }
    }
}
